package sicnu.cs.ich.security.security.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import sicnu.cs.ich.api.domain.form.WechatUserForm;
import sicnu.cs.ich.security.domain.entity.Role;
import sicnu.cs.ich.security.domain.entity.User;
import sicnu.cs.ich.security.exceptions.exception.WechatLoginException;
import sicnu.cs.ich.security.mapper.PermissionMapper;
import sicnu.cs.ich.security.mapper.UserMapper;
import sicnu.cs.ich.security.service.IUserService;

import java.util.stream.Collectors;

/**
 * @author 沈洋 邮箱:1845973183@qq.com
 * @create 2021/12/26-11:07
 **/
@Slf4j
@Service
public class WechatUserServiceImpl {
    //注入登陆的service
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private IUserService userService;
    @Autowired
    private PermissionMapper permissionMapper;
    /**
     * 微信免注册登录
     */
    public UserDetails loadUserByOpenId(WechatUserForm userForm) throws WechatLoginException {
        User user = userMapper.findUserByOpenId(userForm.getOpenId());
        if(user==null){
            log.info("用户不存在，新建用户");
            // 直接构建用户
            user = userService.registerWechatUser(userForm);
        }
        // 加载权限
        if(!CollectionUtils.isEmpty(user.getRoles())){
            var permissions = permissionMapper.findPermissionsByRoles(
                    user.getRoles().stream().map(Role::getId).collect(Collectors.toList()));
            user.setAuthorities(permissions);
        }else throw new UsernameNotFoundException("用户无角色");
        return user;
    }

}
